<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="类别编号" prop="categoryId">
            <el-input v-model="ruleForm.categoryId" />
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryName">
            <el-select v-model="ruleForm.categoryName" placeholder="请选择类别">
                <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
                    :value="item.categoryName" />
            </el-select>
        </el-form-item>
        <el-form-item label="创建日期" prop="createTime">
            <el-date-picker v-model="ruleForm.createTime" type="date" aria-label="请选择" placeholder="请选择"
                style="width: 100%" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
// 表单数据接口
interface RuleForm {
    categoryId: number
    categoryName: string
    createTime: string
}
// 表单属性size
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    categoryId: 1,
    categoryName: '',
    createTime: ''
})

//表单校验规则
const rules = reactive<FormRules<RuleForm>>({
    categoryId: [{ required: true, message: '类别ID不能为空', trigger: 'blur' }],
    categoryName: [{ required: true, message: '类别名称不能为空', trigger: 'change' }],
    createTime: [{ type: 'date', required: true, message: '请选择日期', trigger: 'change' }]
})

/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const form = toRaw(ruleForm)
            ElMessage.success(JSON.stringify(form))
        } else {
            console.log('error submit!', fields)
        }
    })
}

/** 重置表单 */
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 静态指定select的options数据,数组类型
const categoryList = [
    {
        categoryId: 1,
        categoryName: '文具',
        createTime: '2022-05-02'
    },
    {
        categoryId: 2,
        categoryName: '日用品',
        createTime: '2022-05-04'
    },
    {
        categoryId: 3,
        categoryName: '饮料',
        createTime: '2022-05-05'
    },
    {
        categoryId: 4,
        categoryName: '化妆品',
        createTime: '2022-05-06'
    }
]
</script>
